package com.lsh.payment.core.util.pay.cm;

import com.lsh.payment.core.util.Base64;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 19/4/26
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
public class CmSha256 {

    /**
     *
     * @param data
     * @param sign
     * @param publicKey
     * @return
     */
    public static boolean validateSign(String data, String sign, String publicKey) {

        try {

            Signature signature = Signature.getInstance("SHA256WithRSA");
            PublicKey localPublicKey = CmSha256.getPublicKeyFromX509("RSA", publicKey);
            signature.initVerify(localPublicKey);
            signature.update(data.getBytes());

            return signature.verify(Base64.decode(sign));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     *
     * @param algorithm
     * @param publicKey
     * @return
     * @throws Exception
     */
    private static PublicKey getPublicKeyFromX509(String algorithm, String publicKey) throws Exception {

        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(publicKey)));
    }


}
